package main

import (
	"disk/logger"
	"disk/server"
	"disk/server/disk_rpc"
	diskService "disk/server/disk_rpc/service"
	"disk/server/files"
	"disk/server/midware"
	"disk/server/user"
	userService "disk/server/user/dao/service"
	"disk/server/utils"
	"fmt"
	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"log"
)

func main() {
	// 配置相关
	viper.AddConfigPath("./conf/")
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Sprintf("配置文件错误 %s", err.Error()))
	}

	userService.Init()
	diskService.Init()

	// 服务相关
	r := server.CreateServer()
	r.Use(cors.Default())

	serverLogger, _ := logger.InitLogger(zap.DebugLevel)
	defer serverLogger.Sync()
	r.Use(logger.GinLogger(serverLogger), logger.GinRecovery(serverLogger, true))

	utils.PingGET(r)

	Router := r.Group("api/refresh", midware.CheckLogin())
	utils.RefreshGET(Router)

	userRouter := r.Group("api/user")
	userRouter.Use(gin.Logger(), gin.Recovery())
	user.Login(userRouter)
	user.Register(userRouter)
	user.LogoutGet(userRouter)
	user.ChangePwdPost(userRouter)
	user.GetPubKey(userRouter)

	diskRpcRouter := r.Group("api/disk", midware.CheckLogin())
	diskRpcRouter.Use(gin.Logger(), gin.Recovery())
	disk_rpc.Add(diskRpcRouter)
	disk_rpc.Update(diskRpcRouter)
	disk_rpc.Delete(diskRpcRouter)
	disk_rpc.Query(diskRpcRouter)
	disk_rpc.QueryPage(diskRpcRouter)

	filesRouter := r.Group("api/files", midware.CheckLogin())
	filesRouter.Use(gin.Logger(), gin.Recovery())
	files.FileList(filesRouter, nil)
	files.FileDownload(filesRouter, nil)
	files.FileDelete(filesRouter, nil)
	files.FileUpload(filesRouter, nil)
	files.BigFileUpload(filesRouter, nil)

	err := r.Run(viper.GetString("server.addr") + ":" + viper.GetString("server.port"))
	if err != nil {
		log.Println(err.Error())
	}
}
